import { Component, OnInit, ViewChild, ElementRef, Renderer2,AfterViewInit } from '@angular/core';
import {ChangeDetectionStrategy} from '@angular/core';
import {rn, rc, veriString} from '../../utils/num.util';
import {Quote} from '../../domain/quote.model';
import {debounceTime, map} from 'rxjs/operators';
import {QuoteService} from '../../services/quote.service';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {Observable} from 'rxjs';
import {Store, select} from '@ngrx/store';
import * as quoteActions from '../../actions/quote.action';
import * as authActions from '../../actions/auth.action';
import * as fromRoot from '../../reducers';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit , AfterViewInit{
  form:FormGroup;
  quote$:Observable<Quote>;
  @ViewChild('veri') veri: ElementRef;
  w = 120;
  h = 30;
  veriCode: string = '' ;
  constructor(
    private fb:FormBuilder,
    private quoteService:QuoteService,
    private rd: Renderer2,
    private store$:Store<fromRoot.State>
  ) {
    this.quote$ = this.store$.pipe(select(fromRoot.getQuote));
    // this.quoteService.getQuote().subscribe(q=>{
    //   this.store$.dispatch(new actions.LoadSuccessAction(q))
    // })
    //原来是reducer的写法，现在加入effect后被废弃

    this.store$.dispatch(new quoteActions.LoadAction(null));
  }

  ngOnInit() {
    // this.rd.setAttribute(this.veri.nativeElement, 'width', '120');
    // this.rd.setAttribute(this.veri.nativeElement, 'height', '30');
    /*
    this.form = new FormGroup({
      email:new FormControl('hbxyxuxiaodong@163.com',Validators.compose([Validators.required,Validators.email])),
      password:new FormControl('543')
    })
    最原始的写法
    */
   // email:['',Validators.compose([Validators.required,Validators.email])];
    this.form = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required],
      vericode: ['', Validators.required]
    });
  }
  ngAfterViewInit() {
    this.paint();
  }
  paint() {
    this.veriCode = '';
    const ctx = this.veri.nativeElement.getContext('2d');
    ctx.fillStyle = rc(180, 230);
    ctx.fillRect(0, 0, this.w, this.h);
    ctx.textBaseline = 'top';
    const pools = veriString;
    for (let i = 0; i < 4 ; i++) {
        const txt = pools[ rn(0, pools.length)];
        this.veriCode += txt;
        ctx.fillStyle = rc(80, 180);
        ctx.font = rn(10, 20) + 'px Arial';
        const txtwidth = ctx.measureText(txt).width;
        ctx.save();
        ctx.translate(i * 30 + 15, 15);
        ctx.rotate(rn(-12, 12) * Math.PI / 180);
        const x = rn(-15, 15 - txtwidth);
        const y = rn(0, -8 - txtwidth);
        console.log(x, y);
        ctx.fillText(txt, x, y);
        // ctx.fillText(txt, 0, 0);
        ctx.restore();
    }
    for (let i = 0 ; i < 6; i++) {
      ctx.beginPath();
      ctx.moveTo(rn(0, this.w), rn(0, this.h));
      ctx.lineTo(rn(0, this.w), rn(0, this.h));
      ctx.strokeStyle = rc(80, 180);
      ctx.stroke();
    }
  }
  onSubmit({value, valid}, ev: Event) {
    ev.preventDefault();
    this.form.controls['vericode'].setValidators(this.validateCode.bind(this));
    this.form.get('vericode').updateValueAndValidity();
    if ( !this.form.get('vericode').valid) {
      this.paint();
    }
    if (!this.form.valid) {
      return ;
    }
    const newvalue = {...value};
    this.store$.dispatch(new authActions.LoginAction(newvalue));
  }
  validate(c:FormControl):{[key:string]:any}{
    if(!c.value){
      return null
    }
    const pattern = /^wang+/;
    if(pattern.test(c.value)){
      return null
    }
    return {
      email: 'eamil must be start wang'
    };
  }
  validateCode(c: FormControl) {
    console.log(this)
    const  code = c.value;
    const valid = this.veriCode === code ? true : false;
    // valid || this.paint();
    return valid ? null : {code: { descxx: '验证码错误！'}};
  }
}
